use reqwest::Client;

use crate::{
    common::{query_url, Response},
    data_analysis::param::{RetainReq, SummaryTrend, VisitTrendRes},
};

pub async fn get_monthly_trend<T>(
    token: T,
    req: &RetainReq,
) -> Result<Response<VisitTrendRes>, reqwest::Error>
where
    T: AsRef<str>,
{
    let url = "https://api.weixin.qq.com/datacube/getweanalysisappidmonthlyvisittrend";
    get_trend(url, token, req).await
}

pub async fn get_daily_trend<T>(
    token: T,
    req: &RetainReq,
) -> Result<Response<VisitTrendRes>, reqwest::Error>
where
    T: AsRef<str>,
{
    let url = "https://api.weixin.qq.com/datacube/getweanalysisappiddailyvisittrend";
    get_trend(url, token, req).await
}

pub async fn get_weekly_trend<T>(
    token: T,
    req: &RetainReq,
) -> Result<Response<VisitTrendRes>, reqwest::Error>
where
    T: AsRef<str>,
{
    let url = "https://api.weixin.qq.com/datacube/getweanalysisappidweeklyvisittrend";
    get_trend(url, token, req).await
}

async fn get_trend<T, U>(
    url: T,
    token: U,
    req: &RetainReq,
) -> Result<Response<VisitTrendRes>, reqwest::Error>
where
    T: AsRef<str>,
    U: AsRef<str>,
{
    let url = query_url(url, token);
    let client = Client::new();
    client
        .post(url)
        .json(req)
        .send()
        .await?
        .json::<Response<VisitTrendRes>>()
        .await
}

pub async fn get_summary_trend<T>(
    token: T,
    req: &RetainReq,
) -> Result<Response<SummaryTrend>, reqwest::Error>
where
    T: AsRef<str>,
{
    let url = query_url(
        "https://api.weixin.qq.com/datacube/getweanalysisappiddailysummarytrend",
        token,
    );
    let client = Client::new();
    client
        .post(url)
        .json(req)
        .send()
        .await?
        .json::<Response<SummaryTrend>>()
        .await
}
